/**
 * 用户中心状态管理
 */
import { defineStore } from 'pinia';
import { ref } from 'vue';
import { UserInfo } from '@/types';
import { fetchUserInfo, updateUserInfo } from '../services/user';

export const useUserCenterStore = defineStore('userCenter', () => {
  // 状态
  const userInfo = ref<UserInfo | null>(null);
  const loading = ref(false);
  const updating = ref(false);
  const error = ref<Error | null>(null);

  // 获取用户信息
  const getUserInfo = async () => {
    loading.value = true;
    error.value = null;

    try {
      userInfo.value = await fetchUserInfo();
    } catch (err) {
      error.value = err as Error;
      console.error('获取用户信息失败:', err);
    } finally {
      loading.value = false;
    }
  };

  // 更新用户信息
  const updateUser = async (userData: Partial<UserInfo>) => {
    updating.value = true;
    error.value = null;

    try {
      userInfo.value = await updateUserInfo(userData);
      return true;
    } catch (err) {
      error.value = err as Error;
      console.error('更新用户信息失败:', err);
      return false;
    } finally {
      updating.value = false;
    }
  };

  // 重置状态
  const resetState = () => {
    userInfo.value = null;
    loading.value = false;
    updating.value = false;
    error.value = null;
  };

  return {
    // 状态
    userInfo,
    loading,
    updating,
    error,

    // 方法
    getUserInfo,
    updateUser,
    resetState
  };
});
